package com.weiiew.backend.controller;

import com.weiiew.backend.config.ShutdownKeyConfig;
import com.weiiew.backend.utils.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 魏锴
 * @since 2025/6/6
 */
@Slf4j
@RestController
public class ShutdownController {
    @Autowired
    private ConfigurableApplicationContext context;
    @Autowired
    private ShutdownKeyConfig shutdownKeyConfig;

    @RequestMapping("/secure/shutdown")
    public ApiResponse shutdown(String key) {
        // 执行关机命令
        if (shutdownKeyConfig == null || shutdownKeyConfig.shutdownKeyHolder() == null || shutdownKeyConfig.shutdownKeyHolder().get() == null) {
            log.warn("关机密钥配置异常");
            return ApiResponse.failure("关机密钥配置异常");
        }
        // 执行关机命令
        if (!shutdownKeyConfig.shutdownKeyHolder().get().equals(key)) {
            log.warn("密钥错误");
            return ApiResponse.failure("密钥错误");
        }
        new Thread(() -> {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            context.close();
        }).start();
        log.info("关机命令已接受");
        return ApiResponse.ok("关机命令已接受");
    }
}
